package com.lan.iot;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.Gravity;
import android.view.HapticFeedbackConstants;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.lan.iot.entity.AirconditionEntity;
import com.lan.iot.utils.JsonUtil;
import com.lan.iot.utils.OkHttpRequestUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.newland.nle_sdk.requestEntity.SignIn;
import cn.com.newland.nle_sdk.responseEntity.User;
import cn.com.newland.nle_sdk.responseEntity.base.BaseResponseEntity;
import cn.com.newland.nle_sdk.util.NCallBack;
import cn.com.newland.nle_sdk.util.NetWorkBusiness;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class AirCdn extends AppCompatActivity implements CommonPopWindow.ViewClickListener {
    TextView textView;
    int temp = 30;
    int[] id = {R.drawable.snow, R.drawable.sun, R.drawable.fengshan};
    TextView textView1;
    TextView textViewkaiguan;
    ImageView img_moshi;
    int t = 1;
    String[] str = new String[]{"制冷", "制热", "送风"};
    String[] strkaiguan = new String[]{"关", "开"};
    int t1 = 1;
    String[] str1 = new String[]{"低", "中", "高", "自动"};
    private int t_kaiguan = 0;
    private int fs = 1;
    private int ms = 1;
    int open = 0;
    private int saofeng = 0;
    private TextView textViewsaofeng;
    private String kt;
    private String intex = "android.intent.action.CART_BROADCAST_a";
    private int roomid;

    public void moshi() {
        img_moshi.setImageResource(id[t]);
    }

    //    public void fengsu() {
//        textView1.setText(str1[t1]);
//        t1 = (t1 == 3 ? 0 : (t1 + 1));
//    }
    private void airconditionControl() {
        AirconditionEntity airconditionEntity = new AirconditionEntity();
        airconditionEntity.setTemp(temp + "");
        airconditionEntity.setModel(ms);
        airconditionEntity.setWindSpeed(fs);
        airconditionEntity.setDeviceID("638233");
        airconditionEntity.setApiTag(kt);
        airconditionEntity.setIsOpen(open);
        airconditionEntity.setsaofeng(t_kaiguan);
        String bodyJson = JSONObject.toJSONString(airconditionEntity);
//    bodyJson="{\"model\":1,\"delayTime\":0,\"deviceID\":\"638233\",\"apiTag\":\"kt1\",\"temp\":\"30\",\"windSpeed\":1}";
//    bodyJson="{\"apiTag\":\"kt1\",\"deviceID\":\"638233\",\"model\":1,\"temp\":\"30\",\"isOpen\":1,\"windSpeed\":1}";
        if (token != null)
            controlDevice(airconditionEntity.getDeviceID(), airconditionEntity.getApiTag(), bodyJson);
        System.out.println(bodyJson);
    }

    private void controlDevice(String deviceId, String apiTag, String data) {
        //发出网络请求

        String SENSOR_DATA_ALL = "http://api.nlecloud.com/Cmds";
        try {
            Map<String, String> valmap = new HashMap<>();
            valmap.put("deviceId", deviceId);
            valmap.put("apiTag", apiTag);
            Response access = OkHttpRequestUtil.postAccess(SENSOR_DATA_ALL, valmap, data, token);
            if (access.isSuccessful()) {
                ResponseBody body = access.body();
                Map map = JsonUtil.toMap(body.string());
                Double status = (double) map.get("Status");
                Message message = new Message();
                if (status == null || status.intValue() != 0.0) {
                    message.arg1 = 0;
                } else {
                    message.arg1 = 1;
                }
                message.obj = map.get("Msg");
                message.what = 0x01;
                handler.sendMessage(message);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 0x01:
                    int status = msg.arg1;
                    String msgText = "";
                    if (status == 0) {
                        msgText = "控制失败:" + msg.obj;
                    } else if (status == 1) {
                        msgText = "控制成功:" + msg.obj;
                    }
                    Toast.makeText(AirCdn.this, msgText, Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };

    public void cdnControl() {
        AirconditionEntity airconditionEntity = new AirconditionEntity();
        airconditionEntity.setTemp("30");
        airconditionEntity.setModel(1);
        airconditionEntity.setWindSpeed(1);
        airconditionEntity.setDeviceID("638233");
        airconditionEntity.setApiTag("kt1");
        // airconditionControl(airconditionEntity);

        final String val = JSONObject.toJSONString(airconditionEntity);


        new Thread(new Runnable() {
            @Override
            public void run() {

                test(val);
            }
        }).start();
    }

    private void test(String data) {
        //发出网络请求
        String SENSOR_DATA_ALL = "http://api.nlecloud.com/Cmds";
        try {
            Map<String, String> valmap = new HashMap<>();
            valmap.put("deviceId", "638233");
            valmap.put("apiTag", "kt1");
            Response access = OkHttpRequestUtil.postAccess(SENSOR_DATA_ALL, valmap, data, token);
            if (access.isSuccessful()) {
                ResponseBody body = access.body();
                Map map = JsonUtil.toMap(body.string());
                Double status = (double) map.get("Status");
                if (status == null || status.intValue() != 0.0) return;//获取失败
                List<Map<String, Object>> vals = (ArrayList) map.get("ResultObj");

            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }

    }

    String token;
    NetWorkBusiness netWorkBusiness;

    private void init() {
        NetWorkBusiness netWorkBusiness2 = new NetWorkBusiness("", "http://www.nlecloud.com/");
        netWorkBusiness2.signIn(new SignIn("17680316790", "1234567890"), new NCallBack<BaseResponseEntity<User>>(getApplicationContext()) {
            @Override
            protected void onResponse(BaseResponseEntity<User> response) {
                netWorkBusiness = new NetWorkBusiness(response.getResultObj().getAccessToken(), "http://www.nlecloud.com/");
                token = response.getResultObj().getAccessToken();
                if (sw.isChecked()) conACD();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
//                        NlecloudUtil nlecloudUtil=new NlecloudUtil();
//                        nlecloudUtil.gainDevices("596248", token, new NlecloudResponse<List<SensorInfoEntity>>() {
//                            @Override
//                            public void callBack(ResultEntity<List<SensorInfoEntity>> resultEntity) {
//                                List<SensorInfoEntity> resultObj = resultEntity.getResultObj();
//                            }
//                        });
                    }
                }).start();
            }
        });
    }

    private List<GetConfigReq.DatasBean> datasBeanList;

    private void initData() {
        //模拟请求后台返回数据
        String response = "{\"ret\":0,\"msg\":\"succes,\",\"datas\":[{\"ID\":\"  0\",\"categoryName\":\"0.5小时\",\"state\":\"1\"},{\"ID\":\"1\",\"categoryName\":\"1小时\",\"state\":\"1\"},{\"ID\":\"2\",\"categoryName\":\"1.5小时\",\"state\":\"1\"},{\"ID\":\"3\",\"categoryName\":\"2小时\",\"state\":\"1\"},{\"ID\":\"4\",\"categoryName\":\"关\",\"state\":\"1\"}]}";
        GetConfigReq getConfigReq = new Gson().fromJson(response, GetConfigReq.class);
        //0请求表示成功
        if (getConfigReq.getRet() == 0) {
            //滚动选择数据集合
            datasBeanList = getConfigReq.getDatas();
        }
    }

    public void getChildView(final PopupWindow mPopupWindow, View view, int mLayoutResId) {
        switch (mLayoutResId) {
            case R.layout.timese:
                TextView imageBtn = view.findViewById(R.id.img_guanbi);
                PickerScrollView addressSelector = view.findViewById(R.id.address);

                // 设置数据，默认选择第一条
                addressSelector.setData(datasBeanList);
                addressSelector.setSelected(4);

                //滚动监听
                addressSelector.setOnSelectListener(new PickerScrollView.onSelectListener() {
                    @Override
                    public void onSelect(GetConfigReq.DatasBean pickers) {
                        categoryName = pickers.getCategoryName();
                    }
                });

                //完成按钮
                imageBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mPopupWindow.dismiss();
                        if(categoryName==null){
                            categoryName="关";
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    //  controlDevice("638233", "m_fan", 1+"");
                                    controlDevice("638233", "dingshi", "0");
                                }
                            }).start();
                        }else
                        if (categoryName.equals("关")) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    //  controlDevice("638233", "m_fan", 1+"");
                                    controlDevice("638233", "dingshi", "0");
                                }
                            }).start();
                        } else {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    //  controlDevice("638233", "m_fan", 1+"");
                                    controlDevice("638233", "dingshi", "1");
                                }
                            }).start();
                        }
                        textViewkaiguan.setText("定时：" + categoryName);
                    }
                });
                break;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

        Intent intent2 = new Intent(intex);
        intent2.putExtra("acdndata", sw.isChecked());
        intent2.putExtra("roomid", roomid);
        LocalBroadcastManager.getInstance(AirCdn.this).sendBroadcast(intent2);
        sendBroadcast(intent2);
    }

    Switch sw;
    CircleControlView view;
    private String categoryName;

    public void conACD() {
        int id = 0;
        id = temp * 10000 + ms * 1000 + fs * 100 + t_kaiguan * 10 + open;
        if (id % 10 == 0) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //  controlDevice("638233", "m_fan", 1+"");
                    airconditionControl();
                }
            }).start();
            return;
        }
        switch (id) {
//            case 200001:
//            case 260001:
//            case 261111:
//            case 301101:
//            case 200101:
//            case 260101:
//            case 200211:
//            case 260201:
//            case 261201:
//            case 301201:
//            case 261011:
//            case 301001:
//            case 200111:
//            case 200201:
//            case 260011:
//            case 261101:
            case 200001:
            case 200101:
            case 200201:
            case 200211:
            case 201201:
            case 202201:
            case 262201:
            case 302201:
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //  controlDevice("638233", "m_fan", 1+"");
                        airconditionControl();
                    }
                }).start();
            default:
                ;
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            Window window = getWindow();

            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS

                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION

                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);

            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);

            window.setStatusBarColor(Color.TRANSPARENT);

            window.setNavigationBarColor(Color.TRANSPARENT);
        }
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_air_cdn);
        sw = findViewById(R.id.sw);
        sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                open = b ? 1 : 0;
                if (b) {
                    view.mCirqueBgPaint.setColor(0xffffd36a);
                } else {
                    view.mCirqueBgPaint.setColor(0xffe6e6e6);
                }
                view.invalidate();
                conACD();
            }
        });
        Intent intent = this.getIntent();
        Bundle bundle = intent.getExtras();
        kt = bundle.getString("kt", "kt1");
        roomid = bundle.getInt("roomid");
//        if(kt.equals("kt1"))intex="android.intent.action.CART_BROADCAST_a";
//        if(kt.equals("kt2"))intex="android.intent.action.CART_BROADCAST_a_2";
//        if(kt.equals("kt3"))intex="android.intent.action.CART_BROADCAST_a_3";

        boolean isOpen = bundle.getBoolean("name", true);
        init();
        initData();
        img_moshi = findViewById(R.id.img_moshi);
        textViewkaiguan = findViewById(R.id.text_kaiguan);
        textViewsaofeng = findViewById(R.id.text_saofen);
        Button back = findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
//        Button btn = findViewById(R.id.cc);
//        btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
////                new MainActivity1().cdnControl();
////                cdnControl();
//
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        //  controlDevice("638233", "m_fan", 1+"");
//                        airconditionControl();
//                    }
//                }).start();
//            }
//        });
        final TextView t = findViewById(R.id.text);
        textView = findViewById(R.id.text_moshi);
        textView1 = findViewById(R.id.text_fengsu);
        view = findViewById(R.id.c);
        view.setOnTextFinishListener(new CircleControlView.OnCirqueProgressChangeListener() {
            @Override
            public void onChange(int minProgress, int maxProgress, int progress) {
//                int prog = progress;
                temp = progress;
                String s = String.valueOf(progress);
                t.setText("温度：" + s + "℃");
            }

            @Override
            public void onChangeEnd(int minProgress, int maxProgress, int progress) {
//                 temp = progress;
                String s = String.valueOf(progress);
                if (sw.isChecked()) conACD();
//                t.setText("温度：" + s + "℃");
            }
        });
        view.mCurrentAngle=(360/14)*4;
        view.invalidate();
//        Button btn = findViewById(R.id.btn);
        if (isOpen) sw.setChecked(true);
        TextView btn1 = findViewById(R.id.text1);
//        btn1.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Animation shake = AnimationUtils.loadAnimation(AirCdn.this, R.anim.shake);//加载动画资源文件
//                findViewById(R.id.btn1).startAnimation(shake); //给组件播放动画效果
//                moshi();
//            }
//        });
//        TextView btn2 = findViewById(R.id.text2);
//        btn2.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Animation shake = AnimationUtils.loadAnimation(AirCdn.this, R.anim.shake);//加载动画资源文件
//                findViewById(R.id.btn2).startAnimation(shake); //给组件播放动画效果
//                fengsu();
//            }
//        });
//        btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                final Dialog dlg;
//                final Drawable dr = getResources().getDrawable(R.drawable.radius_border_d);
//                dlg = new AlertDialog.Builder(AirCdn.this).create();
//                dlg.show();//显示对话框
//                Window window = dlg.getWindow();//获取对话框窗口\
//                window.setGravity(Gravity.BOTTOM);//设置对话框显示剧中的位置
//                window.setContentView(R.layout.timese);//设置对话框布局
//                window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
//
//                window.setBackgroundDrawable(dr);
//                WindowManager.LayoutParams params = dlg.getWindow()
//                        .getAttributes();
////                Display display = getWindowManager().getDefaultDisplay();
////                params.width = (int) (dpToPx(344));
////                        params.width=dpToPx(360);
////                params.dimAmount = 0.0f;
//                dlg.getWindow().setAttributes(params);
//                Button btn1 = window.findViewById(R.id.no);
//                btn1.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        dlg.cancel();
//                    }
//                });
//                Button btn2 = window.findViewById(R.id.yes);
//                btn2.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        dlg.cancel();
//                    }
//                });
//            }
//        });
    }

    public void moshi(View view) {
        moshi_text();
        moshi();
        if (sw.isChecked()) conACD();
    }

    private void moshi_text() {
        t = (t == 2 ? 0 : (t + 1));
        ms = t;
        textView.setText(str[t]);
    }

    private void fengsu_text() {
        t1 = (t1 == 2 ? 0 : (t1 + 1));
        fs = t1;
        textView1.setText(str1[t1]);
    }

    private void setAddressSelectorPopup(View v) {
        int screenHeigh = getResources().getDisplayMetrics().heightPixels;

        CommonPopWindow.newBuilder()
                .setView(R.layout.timese)
                .setBackgroundDrawable(new BitmapDrawable())
                .setSize(ViewGroup.LayoutParams.MATCH_PARENT, Math.round(screenHeigh * 0.3f))
                .setViewOnClickListener(this)
                .setBackgroundDarkEnable(true)
                .setBackgroundAlpha(0.7f)
                .setBackgroundDrawable(new ColorDrawable(999999))
                .build(this)
                .showAsBottom(v);
    }

    public void fengsu(View view) {
        fengsu_text();
        if (sw.isChecked()) conACD();
    }

    public void kaiguan(View view) {
        textViewkaiguan.setText(strkaiguan[t_kaiguan]);
        t_kaiguan = 1 - t_kaiguan;
    }

    public void dingshi(View view) {
        setAddressSelectorPopup(view);
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    public void saofeng(View view) {
        t_kaiguan = 1 - t_kaiguan;
        textViewsaofeng.setText(strkaiguan[t_kaiguan]);
        if (sw.isChecked())
            conACD();
    }

    public void ceshibutton(View view) {
        int id = 0;
        id = temp * 10000 + ms * 1000 + fs * 100 + t_kaiguan * 10 + open;
        System.out.println(id);
        new Thread(new Runnable() {
            @Override
            public void run() {
                //  controlDevice("638233", "m_fan", 1+"");
                airconditionControl();
            }
        }).start();
        if (id % 10 == 0) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //  controlDevice("638233", "m_fan", 1+"");
                    airconditionControl();
                }
            }).start();
            return;
        }
        switch (id) {
            case 200001:
            case 260001:
            case 261111:
            case 301101:
            case 200101:
            case 260101:
            case 200211:
            case 260201:
            case 261201:
            case 301201:
            case 261011:
            case 301001:
            case 200111:
            case 200201:
            case 260011:
            case 261101:

                break;
            default:
                Toast to = Toast.makeText(this, "当前测试指令不在范围内", Toast.LENGTH_SHORT);
                to.setGravity(Gravity.CENTER, 0, 0);
                to.show();
        }

    }


}
